//
//  cwqMessageTypesVC.m
//  WCN
//
//  Created by 陈武琦 on 16/7/8.
//  Copyright © 2016年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "cwqMessageTypesVC.h"
#import "MJRefresh.h"
#import "WCPopupLayerManager.h"
#import "WCNetworkAccessManager.h"
#import "WCDefaultManager.h"
#import "WCNotifyMessageCell.h"
#import "WCNotifyMessageModel.h"
#import "UITableView+FDTemplateLayoutCell.h"
//#import "WCOrderDetailViewController.h"
#import "UITableView+(removeMjrefreshFooter).h"
#import "WCNOrderDetailVC.h"
#import "WCNMyMessageVC.h"
#import "WCInputMessageVC.h"
#import "WCBPushToolByWsj.h"
#import "WCNAllowBeNursingPeopleVC.h"
#import "WCNJoinMeetingVC.h"
#import "WCNotifyMessageListVC.h"
#import "WSJConversion.h"
#import "XHMessageRootViewController.h"
@interface cwqMessageTypesVC ()

{
    NSInteger _page;
    
    
}
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, strong)WCNotifyMessageModel *lastVonversationModel;


@end

@implementation cwqMessageTypesVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self configUI];
//    [self getLastConversion];
    [self getMessageListIsRecover:YES];
    
    
    
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNewMessageS:) name:@"WechatNewMessageInforNotificaiton" object:nil];
    }
    return self;
}

- (void)getLastConversion{
    NSString *tableName =[WSJConversion getTableName];
    NSString *sql =[NSString stringWithFormat:@"select * from %@ order by rowid desc limit 0,1",tableName];
    NSMutableArray *arr= [WSJConversion searchWithSQL:sql];
    if (arr.count>0) {
        WSJConversion *converson = arr.lastObject;
        [self.dataArray addObject:converson];
    }

}

- (void)receiveNewMessageS:(NSNotification *)not{
    
    NSArray *arr = not.userInfo[@"ConversionAndMessage"];
    
    WSJConversion *conversion =arr[0];
   
    if ([self.dataArray.firstObject isKindOfClass:[WSJConversion class]]) {
        [self.dataArray replaceObjectAtIndex:0 withObject:conversion];
//           [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationBottom];
        [self.tableView reloadData];
    }else{
        [self.dataArray insertObject:conversion atIndex:0];
        [self.tableView reloadData];
    }
    
 
  
    
}

- (void)configUI {
    
    _page = 1;
    self.title = @"消息列表";
    self.tableView.backgroundColor = kAppBg;
    [self.tableView registerNib:[UINib nibWithNibName:@"WCNotifyMessageCell" bundle:nil] forCellReuseIdentifier:@"notifyMessageCellId"];
    weakSelf_define;
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf getMessageListIsRecover:YES];
        
    }];

    
}
- (NSMutableArray *)dataArray{
    if (_dataArray ==nil) {
        _dataArray =[NSMutableArray array];
    }
    return _dataArray;
    
}

- (WCNotifyMessageModel *)lastVonversationModel {
    if (!_lastVonversationModel) {
        
    }
    return _lastVonversationModel;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WCNotifyMessageCell *cell =[WCNotifyMessageCell cellForTableView:tableView indexPath:indexPath];
    cell.model =self.dataArray[indexPath.row];
    [cell setNeedsUpdateConstraints];
    
    [cell updateConstraintsIfNeeded];
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    CGFloat h =[tableView fd_heightForCellWithIdentifier:@"notifyMessageCellId" configuration:^(WCNotifyMessageCell *cell) {
        cell.model =self.dataArray[indexPath.row];
    }];
    return h;
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
    }
    id model =self.dataArray[indexPath.row];
    
    if ([model isKindOfClass:[WSJConversion class]]) {
        
//        [self.navigationController pushViewController:[] animated:<#(BOOL)#>]
        XHMessageRootViewController *conservationsVC = [[XHMessageRootViewController alloc] init];
        conservationsVC.title = @"我的咨询会话";
        [self.navigationController pushViewController:conservationsVC animated:YES];
        
    }else{
        WCNotifyMessageModel *notiModel = model;
        WCNotifyMessageListVC *messageListVC = [[WCNotifyMessageListVC alloc] initWithMessageType:[notiModel.messageType integerValue]];
        
        if ([notiModel.messageStatus integerValue]==1) {
            [self remarkMessageReadwithMessageId:[notiModel.id integerValue]];
        }

        [self.navigationController pushViewController:messageListVC animated:YES];
    }
    
    
//    switch ([model.messageType integerValue]) {
//        case 1:{
//        //订单状态消息
//            
//        }
//            break;
//        case 2:{
//            //订单评论消息
//            
//            
//        }
//            break;
//        case 3:{
//            //普通文本消息
//            
//            
//        }
//            
//            break;
//        case 4:{
//            //发送会议消息
//            
//            
//        }
//            
//            break;
//        case 10:{
//            //留言咨询消息
//            
//            
//        }
//            
//            break;
//        case 20:{
//            //共同护理人消息
//            
//            
//        }
//            
//            break;
//
//            
//        default:
//            break;
//    }
    

    
    
    
}

- (void)remarkMessageReadwithMessageId:(NSInteger )messageId{
    
    
    defineWeakSelf;
    [[WCNetworkAccessManager sharedMg] POST:kMarkNotityMessage parameters:@{@"messageId":@(messageId)} success:^(NSDictionary *responseObject) {
        [WCBPushToolByWsj saveNewBadge:[WCBPushToolByWsj getLatestBadge]-1];
        [weakSelf.tableView.header beginRefreshing];
        [CoreSVP showSVPWithType:CoreSVPTypeBottomMsg Msg:responseObject[@"data"] duration:1 allowEdit:YES beginBlock:nil completeBlock:nil];
    } failure:nil netError:nil always:^{
        
    }];
    
}

#pragma mark -请求数据
- (void)getMessageListIsRecover:(BOOL)isRecover{
    //targetId:接收消息人ID(必填)
    //targetType:接收消息人类型(必填 1.护士 2.患者)
    NSMutableDictionary *params =[NSMutableDictionary new];
    params[@"targetId"] =@([[[[WCDefaultManager shareMg] account] stringId] integerValue]);
    params[@"targetType"] =@(1);
    [WCPopupLayerManager showLodingView];
    weakSelf_define;
    [[WCNetworkAccessManager sharedMg] POST:kNotifyMessageTypes parameters:params success:^(NSDictionary  *responseObject) {
        NSArray *array =responseObject[@"data"];
        NSMutableArray *muarr = [NSMutableArray array];
        if (weakSelf.lastVonversationModel) {
            [muarr addObject:weakSelf.lastVonversationModel];
        }
        for (NSDictionary *dict in array) {
            WCNotifyMessageModel *model =[[WCNotifyMessageModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [muarr addObject:model];
        }
        id firstModel =weakSelf.dataArray.firstObject;
      
      
       
        weakSelf.dataArray = muarr;
        if ([firstModel isKindOfClass:[WSJConversion class]]) {
            [weakSelf.dataArray insertObject:firstModel atIndex:0];
        }
      
        
        [weakSelf.tableView reloadData];
    } failure:nil netError:nil always:^{
        [weakSelf.tableView.header endRefreshing];
        [WCPopupLayerManager dissmissLodingView];
    }];
    
    
//    addDate = 1458212828467;
//    id = 507;
//    messageContent = "\U6709\U60a3\U8005\U4e0a\U4f20\U4e86\U6863\U6848\Uff0c\U8bf7\U53ca\U65f6\U67e5\U770b\Uff0c\U8c22\U8c22\U3002";
//    messageStatus = 2;
//    messageTitle = "\U60a3\U8005\U6863\U6848\U901a\U77e5:";
//    messageType = 3;
//    sourceId = 45;
//    targetId = 475;
//    targetType = 1;
//    updateDate = 1458212828467;

}
@end
